# -*- coding: utf-8 -*-
import json

import xmltodict
from django.http import HttpResponse
from django.views.decorators.http import require_POST, require_GET

from common.mch import handler as mch_handler
from common.recharge import db as recharge_db
from common.third import hydra, hydra_withdraw, group_withdraw, meifubao_withdraw, kyjhpay_withdraw, \
    xinglongpay_withdraw, flashpay_withdraw
from common.third import miidow as miidow_withdraw
from common.third import qiji as qiji_withdraw
from common.third import tonglue_withdraw
from common.third import onepay_withdraw
from common.timer import TIMER_EVENT_TYPE
from common.timer.handler import submit_notify_event
from common.utils import track_logging
from common.utils.decorator import response_wrapper
from common.withdraw import db as withdraw_db
from common.withdraw.model import WITHDRAW_ORDER_STATUS

_LOGGER = track_logging.getLogger('third')


@require_POST
@response_wrapper
def notify_qa(request):
    ''' 同略回调[充值] '''
    params = json.loads(request.body.decode('utf-8'))
    _LOGGER.info('tonglue notify: %s', params)
    order = params.get('order_id', None)
    order_id = int(order.split('_')[1])
    unix_timestamp = params.get('verified_time', None)
    if order_id and unix_timestamp:
        order = recharge_db.add_order_success(order_id)
        # order = recharge_db.get_order(int(order_id))
        # datetime_timestamp = datetime.datetime.fromtimestamp(int(unix_timestamp))
        # 已透過財務系統手動回調
        # if order.status != RECHARGE_ORDER_STATUS.DONE:
        #    order.status = RECHARGE_ORDER_STATUS.DONE
        #    order.updated_at = datetime_timestamp
        #    order.save()
        success, _ = mch_handler.notify_mch(order)
        if not success:
            submit_notify_event(order, TIMER_EVENT_TYPE.MCH_NOTIFY)
    return HttpResponse(json.dumps({"success": 1}))


@require_POST
@response_wrapper
def qiji_notify(request, app_id):
    ''' 奇迹回调[提现] '''
    try:
        data = json.loads(request.body.decode('utf-8'))
    except:
        data = request.POST.dict()
    _LOGGER.info('qiji withdraw notify: %s ', data)
    order = withdraw_db.get_order(data['code_id'])

    if order.status != WITHDRAW_ORDER_STATUS.THIRD:
        return HttpResponse("FAIL")

    withdraw_success = qiji_withdraw.check_bankcard_withdraw_notify(data, app_id, order)
    if withdraw_success:
        notify_success, _ = mch_handler.notify_mch_withdraw(order)
        if not notify_success:
            submit_notify_event(order, TIMER_EVENT_TYPE.MCH_WITHDRAW_NOTIFY)
    return HttpResponse("SUCCESS")


@require_POST
@response_wrapper
def miidow_notify(request):
    ''' MIIDOW回调[提现] '''
    _LOGGER.info('miidow withdraw notify: %s ', request.body)
    data = xmltodict.parse(request.body.replace('xmlStr=', '').decode('utf-8'))['request']
    _LOGGER.info('miidow withdraw notify: %s ', data)
    order = withdraw_db.get_order(data['transactionId'])

    if order.status != WITHDRAW_ORDER_STATUS.THIRD:
        return HttpResponse(
            '<?xml version="1.0" encoding="UTF-8" ?> <response><returnStatus> <code>001</code></returnStatus> </response>')

    withdraw_success = miidow_withdraw.check_bankcard_withdraw_notify(data, order)
    if withdraw_success:
        notify_success, _ = mch_handler.notify_mch_withdraw(order)
        if not notify_success:
            submit_notify_event(order, TIMER_EVENT_TYPE.MCH_WITHDRAW_NOTIFY)
    return HttpResponse(
        '<?xml version="1.0" encoding="UTF-8" ?> <response><returnStatus> <code>001</code></returnStatus> </response>')


@require_POST
@response_wrapper
def tonglue_withdraw_notify(request):
    ''' 同略回调[提现] '''
    _LOGGER.info('tonglue withdraw notify: %s ', request.body)
    data = request.body.decode('utf-8')
    order_id = json.loads(data)['order_number']
    order = withdraw_db.get_order(order_id)

    _LOGGER.info(request.META)
    sign = request.META['HTTP_TLYHMAC']

    if not order or order.status != WITHDRAW_ORDER_STATUS.THIRD:
        _LOGGER.info('tonglue withdraw notify order not valid: %s ', order_id)
        return HttpResponse('SUCCESS')

    withdraw_success = tonglue_withdraw.check_bankcard_withdraw_notify(data, sign, order)
    _LOGGER.info('tonglue withdraw notify order %s: %s ', (order_id, withdraw_success))
    if withdraw_success:
        notify_success, _ = mch_handler.notify_mch_withdraw(order)
        if not notify_success:
            submit_notify_event(order, TIMER_EVENT_TYPE.MCH_WITHDRAW_NOTIFY)
    return HttpResponse('SUCCESS')


@require_POST
def hydra_notify(request, app_id):
    try:
        _LOGGER.info('hydra notify: %s ', request.body)
        hydra.check_notify_sign(request, app_id)
        return HttpResponse('SUCCESS', status=200)
    except Exception as e:
        _LOGGER.exception('hydra notify exception.(%s)' % e)
        return HttpResponse('SUCCESS', status=200)


@require_POST
def hydra_withdraw_notify(request, app_id):
    try:
        _LOGGER.info('hydra_withdraw_notify : %s ', request.body)
        hydra_withdraw.check_notify_sign(request, app_id)
        return HttpResponse('SUCCESS', status=200)
    except Exception as e:
        _LOGGER.exception('hydra notify exception.(%s)' % e)
        return HttpResponse('SUCCESS', status=200)


@require_POST
def group_withdraw_notify(request, app_id):
    try:
        _LOGGER.info('group_withdraw_notify : %s ', request.body)
        group_withdraw.check_notify_sign(request, app_id)
        return HttpResponse('''{"status": 0} ''', status=200)
    except Exception as e:
        _LOGGER.exception('group withdraw notify exception.(%s)' % e)
        return HttpResponse('''{"status": 0} ''', status=200)


@require_POST
def meifubao_withdraw_notify(request, app_id):
    try:
        _LOGGER.info('meifubao_withdraw_notify : %s ', request.body)
        meifubao_withdraw.check_notify_sign(request, app_id)
        return HttpResponse('00', status=200)
    except Exception as e:
        _LOGGER.exception('meifubao withdraw notify exception.(%s)' % e)
        return HttpResponse('00', status=200)


@require_POST
def onepay_withdraw_notify(request, app_id, order_id):
    try:
        _LOGGER.info('onepay_withdraw_notify : %s ', request.body)
        onepay_withdraw.check_notify_sign(request, app_id, order_id)
        return HttpResponse('00', status=200)
    except Exception as e:
        _LOGGER.exception('onpay withdraw notify exception.(%s)' % e)
        return HttpResponse('00', status=200)


@require_GET
def kyjhpay_withdraw_notify(request, app_id):
    try:
        _LOGGER.info('kyjhpay_withdraw_notify : %s ', request.GET.dict())
        kyjhpay_withdraw.check_bankcard_withdraw_notify(request, app_id)
        return HttpResponse('SUCCESS', status=200)
    except Exception as e:
        _LOGGER.exception('kyjhpay withdraw notify exception.(%s)' % e)
        return HttpResponse('FAIL', status=200)


@require_POST
def xinglongpay_withdraw_notify(request):
    ''' 兴隆回调[提现] '''
    try:
        _LOGGER.info(u'xinglongpay_withdraw_notify : %s ', request.body)
        xinglongpay_withdraw.check_notify_sign(request)
        return HttpResponse('{"code": "0000"}', status=200)
    except Exception as e:
        _LOGGER.exception('xinglongpay_withdraw notify exception.(%s)' % e)
        return HttpResponse('{"code": "1111"}', status=200)


@require_POST
def flashpay_withdraw_notify(request, app_id):
    try:
        _LOGGER.info(u'flashpay_withdraw_notify : %s ', request.body)
        flashpay_withdraw.check_notify_sign(request, app_id)
        return HttpResponse('SUCCESS', status=200)
    except Exception as e:
        _LOGGER.exception(u'flashpay_withdraw notify exception.(%s)' % e)
        return HttpResponse('FAIL', status=200)
